package com.yanqu.road.server.manager.activity.QixiCrossMgr;

import com.yanqu.road.dao.impl.activity.qixi.QixiDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.qixi.QixiBroadcastData;
import com.yanqu.road.logic.activity.qixi.QixiConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.QixiProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class CrossQixiActivity {
    private int activityId;

    private Map<Long, QixiBroadcastData> qixiBroadcastDataMap = new ConcurrentHashMap<>();
    private List<QixiBroadcastData> needInsertBroadcastDataList = new ArrayList<>();

    /**
     * 活动内的广播id
     */
    private AtomicLong broadcastId = new AtomicLong(1);

    public CrossQixiActivity(ActivityInfo activityInfo) {
        this.activityId = activityInfo.getActivityId();
        loadDb();
    }

    private void loadDb() {
        long validTime = DateHelper.getCurrentTime() - CrossQixiConfigMgr.getConfig(activityId).getQIXI_BROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS - 10 * DateHelper.SECOND_MILLIONS;
        Map<Long, QixiBroadcastData> tempDataMap = new QixiDaoImpl().getQixiBroadcastDataMap(activityId, validTime);
        long maxBroadcastId = new QixiDaoImpl().getMaxBroadcastId(activityId);
        broadcastId.set(maxBroadcastId + 1);
        qixiBroadcastDataMap = tempDataMap;
    }


    public int getActivityId() {
        return activityId;
    }

    public void receiveBroadcastMsg(QixiProto.CorssQixiFlowerBroadcastMsg resultMsg) {
        QixiBroadcastData qixiBroadcastData = new QixiBroadcastData(resultMsg.getActivityId(), broadcastId.getAndIncrement());
        qixiBroadcastData.setContent(resultMsg.getContent());
        qixiBroadcastData.setSendUserId(resultMsg.getLeftUserId());
        qixiBroadcastData.setReceiveUserId(resultMsg.getRightUserId());
        qixiBroadcastData.setSendUserBaseInfo(PlayerBasePb.parseToUserBaseInfo(resultMsg.getLeftUserInfo()));
        qixiBroadcastData.setReceiveUserBaseInfo(PlayerBasePb.parseToUserBaseInfo(resultMsg.getRightUserInfo()));
        qixiBroadcastData.setFlowerId(resultMsg.getFlowerId());
        qixiBroadcastData.setTime(resultMsg.getSendTime());

        synchronized (qixiBroadcastDataMap) {
            if (!qixiBroadcastDataMap.containsKey(qixiBroadcastData.getBroadcastId())) {
                needInsertBroadcastDataList.add(qixiBroadcastData);
            }

            qixiBroadcastDataMap.put(qixiBroadcastData.getBroadcastId(), qixiBroadcastData);
        }
        QixiProto.QixiFlowerBroadcastMsg.Builder builder = CrossQixiMgr.parseBroadcastMsg(qixiBroadcastData);

        for (Long serverId : CrossQixiConfigMgr.getConfig(activityId).getActivityInfo().getServerIdList()) {
            QixiProto.CrossQixiBroadcastBackMsg.Builder backMsg = QixiProto.CrossQixiBroadcastBackMsg.newBuilder();
            backMsg.setTargetUserId(0);
            backMsg.addBroadcastList(builder);
            MessageHelper.sendPacket(serverId, 0,
                    YanQuMessageUtils.buildMessage(GameProtocol.S_QIXI_FLOWER_BROADCAST, backMsg));
        }

    }

    public List<QixiBroadcastData> getBroadcastDataList() {
        List<QixiBroadcastData> list;
        synchronized (qixiBroadcastDataMap) {
            list = new ArrayList<>(qixiBroadcastDataMap.values());
        }
        return list;
    }

    public void loginGetBroadcastMsg(long serverId, long userId, List<Long> excludeId) {
        QixiConfig config = CrossQixiConfigMgr.getConfig(activityId);
        if (config == null) {
            return;
        }

        List<QixiBroadcastData> list = getBroadcastDataList();

        long currentTime = DateHelper.getCurrentTime();

        QixiProto.CrossQixiBroadcastBackMsg.Builder backMsg = QixiProto.CrossQixiBroadcastBackMsg.newBuilder();
        backMsg.setTargetUserId(userId);
        for (QixiBroadcastData qixiBroadcastData : list) {
            if (excludeId.contains(qixiBroadcastData.getBroadcastId())) {
                continue;
            }

            if (qixiBroadcastData.getTime() + config.getQIXI_BROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS < currentTime) {
                continue;
            }

            backMsg.addBroadcastList(CrossQixiMgr.parseBroadcastMsg(qixiBroadcastData));
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(GameProtocol.S_QIXI_FLOWER_BROADCAST, backMsg));
    }

    public QixiBroadcastData getBroadcastData(long broadcastId) {
        return qixiBroadcastDataMap.get(broadcastId);
    }

    public QixiProto.CrossGetBroadcastRewardRespMsg.Builder getBroadcastReward(long broadcastId) {
        QixiProto.CrossGetBroadcastRewardRespMsg.Builder builder = QixiProto.CrossGetBroadcastRewardRespMsg.newBuilder();
        builder.setRet(0);
        QixiBroadcastData broadcastData = getBroadcastData(broadcastId);
        if (broadcastData == null) {
            return builder.setRet(GameErrorCode.E_QIXI_BROADCAST_NOT_FOUND);
        }
        if (broadcastData.getTime() + CrossQixiConfigMgr.getConfig(activityId).getQIXI_BROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS < DateHelper.getCurrentTime()) {
            return builder.setRet(GameErrorCode.E_QIXI_BROADCAST_OVER_TIME);
        }
        builder.setActivityId(activityId);
        builder.setFlowerId(broadcastData.getFlowerId());
        builder.setBroadcastId(broadcastId);

        return builder;
    }

    public List<QixiBroadcastData> popNeedInsertList() {
        List<QixiBroadcastData> list = new ArrayList<>();
        synchronized (qixiBroadcastDataMap) {
            list.addAll(needInsertBroadcastDataList);
            needInsertBroadcastDataList.clear();
        }
        return list;
    }

    public void save() {
        List<QixiBroadcastData> list = popNeedInsertList();
        new QixiDaoImpl().saveQixiBroadcastDataList(list);

        List<QixiBroadcastData> broadcastDataList = getBroadcastDataList();
        if (!broadcastDataList.isEmpty()) {
            synchronized (qixiBroadcastDataMap) {
                for (QixiBroadcastData broadcastData : broadcastDataList) {
                    if (broadcastData.getTime() + CrossQixiConfigMgr.getConfig(activityId).getQIXI_BROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS < DateHelper.getCurrentTime()) {
                        qixiBroadcastDataMap.remove(broadcastData.getBroadcastId());
                    }
                }
            }
        }
    }
}
